import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Like } from 'typeorm';
import { User, SubscriptionType, UserRole } from './entities/user.entity';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';

/**
 * 用户服务
 */
@Injectable()
export class UsersService {
  constructor(
    @InjectRepository(User)
    private usersRepository: Repository<User>,
  ) {}

  /**
   * 创建用户
   */
  async create(createUserDto: CreateUserDto): Promise<User> {
    const user = this.usersRepository.create(createUserDto);
    return await this.usersRepository.save(user);
  }

  /**
   * 查询所有用户（支持分页和搜索）
   */
  async findAll(params?: {
    page?: number;
    limit?: number;
    search?: string;
  }): Promise<{ data: User[]; total: number; page: number; limit: number }> {
    const { page = 1, limit = 20, search } = params || {};

    const queryBuilder = this.usersRepository.createQueryBuilder('user');

    if (search) {
      queryBuilder.where(
        '(user.email LIKE :search OR user.nickname LIKE :search)',
        { search: `%${search}%` },
      );
    }

    queryBuilder.orderBy('user.createdAt', 'DESC');

    const skip = (page - 1) * limit;
    queryBuilder.skip(skip).take(limit);

    const [data, total] = await queryBuilder.getManyAndCount();

    return {
      data,
      total,
      page,
      limit,
    };
  }

  /**
   * 查询单个用户
   */
  async findOne(id: number): Promise<User> {
    const user = await this.usersRepository.findOne({ where: { id } });
    if (!user) {
      throw new NotFoundException(`用户 #${id} 不存在`);
    }
    return user;
  }

  /**
   * 通过邮箱查询用户
   */
  async findByEmail(email: string): Promise<User | null> {
    return await this.usersRepository.findOne({ where: { email } });
  }

  /**
   * 更新用户
   */
  async update(id: number, updateUserDto: UpdateUserDto): Promise<User> {
    const user = await this.findOne(id);
    Object.assign(user, updateUserDto);
    return await this.usersRepository.save(user);
  }

  /**
   * 删除用户
   */
  async remove(id: number): Promise<void> {
    const user = await this.findOne(id);
    await this.usersRepository.remove(user);
  }

  /**
   * 更新用户角色
   */
  async updateRole(id: number, role: UserRole): Promise<User> {
    const user = await this.findOne(id);
    user.role = role;
    return await this.usersRepository.save(user);
  }

  /**
   * 更新用户订阅
   */
  async updateSubscription(
    userId: number,
    subscriptionType: SubscriptionType,
    months: number,
  ): Promise<User> {
    console.log('\n========== 👤 更新用户订阅 ==========');
    console.log('⏰ 时间:', new Date().toISOString());
    console.log('📦 参数:', {
      用户ID: userId,
      订阅类型: subscriptionType,
      月数: months,
    });

    const user = await this.findOne(userId);
    
    console.log('📋 用户当前信息:', {
      用户ID: user.id,
      邮箱: user.email,
      昵称: user.nickname,
      当前订阅类型: user.subscriptionType,
      当前订阅结束日期: user.subscriptionEndDate,
      当前角色: user.role,
    });

    // 更新订阅类型
    user.subscriptionType = subscriptionType;
    
    // 计算订阅结束日期
    const now = new Date();
    const endDate = new Date(now);
    endDate.setMonth(endDate.getMonth() + months);
    user.subscriptionEndDate = endDate;
    
    console.log('🔄 更新后的信息:', {
      新订阅类型: user.subscriptionType,
      新订阅结束日期: user.subscriptionEndDate,
    });

    const savedUser = await this.usersRepository.save(user);
    
    console.log('✅ 用户订阅更新成功:', {
      用户ID: savedUser.id,
      订阅类型: savedUser.subscriptionType,
      订阅结束日期: savedUser.subscriptionEndDate,
      isPremium: savedUser.isPremium,
    });
    console.log('========== ✅ 更新完成 ==========\n');
    
    return savedUser;
  }

  /**
   * 检查用户是否有权限访问高级功能
   */
  async checkPremiumAccess(userId: number): Promise<boolean> {
    const user = await this.findOne(userId);
    return user.isPremium;
  }
}





